package state.old;

public class GumballMachine {
    final static int SOLD_OUT = 0;
    final static int NO_QUARTER = 1;
    final static int HAS_QUARTER = 2;
    final static int SOLD = 3;

    int state = SOLD_OUT;
    int count = 0;

    public GumballMachine(int count) {
        this.count = count;
        if (count > 0) {
            state = NO_QUARTER;
        }
    }

    //付款
    public void insertQuarter() {
        switch (state) {
            case HAS_QUARTER:
                System.out.println("已经付过钱了");
                break;
            case NO_QUARTER:
                System.out.println("请投入25分来购买糖果");
                break;
            case SOLD_OUT:
                System.out.println("售罄");
                break;
            case SOLD:
                System.out.println("请稍等,糖果正在出货中");
                break;
        }
    }

    //退款
    public void ejectQuarter() {
        switch (state) {
            case HAS_QUARTER:
                System.out.println("已经退款了");
                break;
            case NO_QUARTER:
            case SOLD_OUT:
                System.out.println("未付款");
                break;
            case SOLD:
                System.out.println("已经拿到糖果了");
                break;
        }
    }

    //转动曲柄
    public void turnCrank() {
        switch (state) {
            case SOLD:
                System.out.println("警告:尝试取货两次");
                break;
            case NO_QUARTER:
                System.out.println("请先投币");
                break;
            case SOLD_OUT:
                System.out.println("售罄");
                break;
            case HAS_QUARTER:
                System.out.println("收货,请拿走糖果");
                state = SOLD;
                dispense();
                break;
        }
    }

    private void dispense() {
        switch (state) {
            case SOLD:
                System.out.println("售出1糖果");
                count -= 1;
                if (count == 0) {
                    System.out.println("稍等,我们正在处理售罄");
                    state = SOLD_OUT;
                } else {
                    state = NO_QUARTER;
                }
                break;
            case NO_QUARTER:
                System.out.println("请先付款");
                break;
            case SOLD_OUT:
            case HAS_QUARTER:
                System.out.println("警告");
                break;
        }
    }
}
